<template>
<view class="content">
	<view :style='{"minHeight":"100%","width":"100%","padding":"0","position":"relative","background":"#fff","height":"auto"}'>
		<form :style='{"width":"100%","padding":"24rpx","background":"none","display":"block","height":"auto"}' class="app-update-pv">
			<view :style='{"padding":"12rpx 0","margin":"0 0 24rpx 0","borderColor":"rgb(119, 47, 26)","alignItems":"center","borderWidth":"0","display":"flex","width":"100%","borderStyle":"solid","height":"auto"}' class="">
				<view :style='{"padding":"0 10rpx 0 0","whiteSpace":"nowrap","color":"#000000","textAlign":"right","width":"auto","lineHeight":"80rpx","fontSize":"28rpx","fontWeight":"600"}' class="title">订单编号</view>
				<view :style='{"padding":"0px 24rpx","margin":"0px","borderColor":"#808080","color":"rgb(0, 0, 0)","flex":"1","borderWidth":"0 0 2rpx 0","lineHeight":"80rpx","fontSize":"28rpx","borderStyle":"solid"}' class="right-input">
					{{ruleForm.dingdanbianhao}}
				</view>
			</view>
			<view :style='{"padding":"12rpx 0","margin":"0 0 24rpx 0","borderColor":"rgb(119, 47, 26)","alignItems":"center","borderWidth":"0","display":"flex","width":"100%","borderStyle":"solid","height":"auto"}' class="">
				<view :style='{"padding":"0 10rpx 0 0","whiteSpace":"nowrap","color":"#000000","textAlign":"right","width":"auto","lineHeight":"80rpx","fontSize":"28rpx","fontWeight":"600"}' class="title">礼品名称</view>
				<input :style='{"padding":"0px 24rpx","margin":"0px","borderColor":"#808080","color":"rgb(0, 0, 0)","flex":"1","borderWidth":"0 0 2rpx 0","lineHeight":"80rpx","fontSize":"28rpx","borderStyle":"solid"}' :disabled="ro.lipinmingcheng" v-model="ruleForm.lipinmingcheng" placeholder="礼品名称"  type="text"></input>
			</view>
			<view :style='{"padding":"12rpx 0","margin":"0 0 24rpx 0","borderColor":"rgb(119, 47, 26)","alignItems":"center","borderWidth":"0","display":"flex","width":"100%","borderStyle":"solid","height":"auto"}' class="" @tap="lipintupianTap">
				<view :style='{"padding":"0 10rpx 0 0","whiteSpace":"nowrap","color":"#000000","textAlign":"right","width":"auto","lineHeight":"80rpx","fontSize":"28rpx","fontWeight":"600"}' class="title">礼品图片</view>
				<image :style='{"width":"80rpx","borderRadius":"100%","objectFit":"cover","display":"block","height":"80rpx"}' class="avator" v-if="ruleForm.lipintupian" :src="baseUrl+ruleForm.lipintupian.split(',')[0]" mode="aspectFill"></image>
				<image :style='{"width":"80rpx","borderRadius":"100%","objectFit":"cover","display":"block","height":"80rpx"}' class="avator" v-else src="../../static/gen/upload.png" mode="aspectFill"></image>
			</view>
			<view :style='{"padding":"12rpx 0","margin":"0 0 24rpx 0","borderColor":"rgb(119, 47, 26)","alignItems":"center","borderWidth":"0","display":"flex","width":"100%","borderStyle":"solid","height":"auto"}' class="">
				<view :style='{"padding":"0 10rpx 0 0","whiteSpace":"nowrap","color":"#000000","textAlign":"right","width":"auto","lineHeight":"80rpx","fontSize":"28rpx","fontWeight":"600"}' class="title">兑换数量</view>
				<input :style='{"padding":"0px 24rpx","margin":"0px","borderColor":"#808080","color":"rgb(0, 0, 0)","flex":"1","borderWidth":"0 0 2rpx 0","lineHeight":"80rpx","fontSize":"28rpx","borderStyle":"solid"}' :disabled="ro.shuliang" v-model.number="ruleForm.shuliang" placeholder="请输入兑换数量" type="number" required></input>
			</view>
			<view :style='{"padding":"12rpx 0","margin":"0 0 24rpx 0","borderColor":"rgb(119, 47, 26)","alignItems":"center","borderWidth":"0","display":"flex","width":"100%","borderStyle":"solid","height":"auto"}' class="">
				<view :style='{"padding":"0 10rpx 0 0","whiteSpace":"nowrap","color":"#000000","textAlign":"right","width":"auto","lineHeight":"80rpx","fontSize":"28rpx","fontWeight":"600"}' class="title">兑换积分</view>
				<input :style='{"padding":"0px 24rpx","margin":"0px","borderColor":"#808080","color":"rgb(0, 0, 0)","flex":"1","borderWidth":"0 0 2rpx 0","lineHeight":"80rpx","fontSize":"28rpx","borderStyle":"solid"}' :disabled="ro.duihuanjifen" v-model.number="ruleForm.duihuanjifen" placeholder="兑换积分" type="digit"></input>
			</view>
			<view :style='{"padding":"12rpx 0","margin":"0 0 24rpx 0","borderColor":"rgb(119, 47, 26)","alignItems":"center","borderWidth":"0","display":"flex","width":"100%","borderStyle":"solid","height":"auto"}' class="">
				<view :style='{"padding":"0 10rpx 0 0","whiteSpace":"nowrap","color":"#000000","textAlign":"right","width":"auto","lineHeight":"80rpx","fontSize":"28rpx","fontWeight":"600"}' class="title">应付积分</view>
				<view :style='{"padding":"0px 24rpx","margin":"0px","borderColor":"#808080","color":"rgb(0, 0, 0)","flex":"1","borderWidth":"0 0 2rpx 0","lineHeight":"80rpx","fontSize":"28rpx","borderStyle":"solid"}' class="right-input">
					{{jifen}}
				</view>
			</view>
			<view :style='{"padding":"12rpx 0","margin":"0 0 24rpx 0","borderColor":"rgb(119, 47, 26)","alignItems":"center","borderWidth":"0","display":"flex","width":"100%","borderStyle":"solid","height":"auto"}' class="">
				<view :style='{"padding":"0 10rpx 0 0","whiteSpace":"nowrap","color":"#000000","textAlign":"right","width":"auto","lineHeight":"80rpx","fontSize":"28rpx","fontWeight":"600"}' class="title">订单时间</view>
				<input :disabled="ro.dingdanshijian" :style='{"padding":"0px 24rpx","margin":"0px","borderColor":"#808080","color":"rgb(0, 0, 0)","flex":"1","borderWidth":"0 0 2rpx 0","lineHeight":"80rpx","fontSize":"28rpx","borderStyle":"solid"}' v-model="ruleForm.dingdanshijian" placeholder="订单时间" @tap="toggleTab('dingdanshijian')"></input>
			</view>
			<view :style='{"padding":"12rpx 0","margin":"0 0 24rpx 0","borderColor":"rgb(119, 47, 26)","alignItems":"center","borderWidth":"0","display":"flex","width":"100%","borderStyle":"solid","height":"auto"}' class="">
				<view :style='{"padding":"0 10rpx 0 0","whiteSpace":"nowrap","color":"#000000","textAlign":"right","width":"auto","lineHeight":"80rpx","fontSize":"28rpx","fontWeight":"600"}' class="title">用户积分</view>
				<input :style='{"padding":"0px 24rpx","margin":"0px","borderColor":"#808080","color":"rgb(0, 0, 0)","flex":"1","borderWidth":"0 0 2rpx 0","lineHeight":"80rpx","fontSize":"28rpx","borderStyle":"solid"}' :disabled="ro.yonghujifen" v-model.number="ruleForm.yonghujifen" placeholder="用户积分" type="digit"></input>
			</view>
			<view :style='{"padding":"12rpx 0","margin":"0 0 24rpx 0","borderColor":"rgb(119, 47, 26)","alignItems":"center","borderWidth":"0","display":"flex","width":"100%","borderStyle":"solid","height":"auto"}' class="">
				<view :style='{"padding":"0 10rpx 0 0","whiteSpace":"nowrap","color":"#000000","textAlign":"right","width":"auto","lineHeight":"80rpx","fontSize":"28rpx","fontWeight":"600"}' class="title">兑换者</view>
				<input :style='{"padding":"0px 24rpx","margin":"0px","borderColor":"#808080","color":"rgb(0, 0, 0)","flex":"1","borderWidth":"0 0 2rpx 0","lineHeight":"80rpx","fontSize":"28rpx","borderStyle":"solid"}' :disabled="ro.duihuanzhe" v-model="ruleForm.duihuanzhe" placeholder="兑换者"  type="text"></input>
			</view>
			<view :style='{"padding":"12rpx 0","margin":"0 0 24rpx 0","borderColor":"rgb(119, 47, 26)","alignItems":"center","borderWidth":"0","display":"flex","width":"100%","borderStyle":"solid","height":"auto"}' class="">
				<view :style='{"padding":"0 10rpx 0 0","whiteSpace":"nowrap","color":"#000000","textAlign":"right","width":"auto","lineHeight":"80rpx","fontSize":"28rpx","fontWeight":"600"}' class="title">服务地址</view>
				<input :style='{"padding":"0px 24rpx","margin":"0px","borderColor":"#808080","color":"rgb(0, 0, 0)","flex":"1","borderWidth":"0 0 2rpx 0","lineHeight":"80rpx","fontSize":"28rpx","borderStyle":"solid"}' :disabled="ro.zhuzhi" v-model="ruleForm.zhuzhi" placeholder="服务地址"  type="text"></input>
			</view>
			<view :style='{"padding":"12rpx 0","margin":"0 0 24rpx 0","borderColor":"rgb(119, 47, 26)","alignItems":"flex-start","borderWidth":"0","display":"flex","width":"100%","borderStyle":"solid","height":"auto"}' class="">
				<view :style='{"padding":"0 10rpx 0 0","whiteSpace":"nowrap","color":"#000000","textAlign":"right","width":"auto","lineHeight":"80rpx","fontSize":"28rpx","fontWeight":"600"}' class="title">订单备注</view>
				<textarea :style='{"padding":"20rpx 24rpx","margin":"0px","borderColor":"#808080","color":"rgb(0, 0, 0)","flex":"1","borderWidth":"2rpx","fontSize":"28rpx","borderRadius":"12rpx","borderStyle":"solid","height":"200rpx"}' v-model="ruleForm.dingdanbeizhu" placeholder="订单备注" :maxlength="-1"></textarea>
			</view>
			
			<view :style='{"width":"100%","justifyContent":"space-between","display":"flex","height":"auto"}' class="btn" >
				<button :style='{"border":"0","padding":"0px","margin":"0","color":"#fff","background":"linear-gradient( 135deg, #9EF0EA 0%, #99ABFF 100%)","width":"48%","lineHeight":"80rpx","fontSize":"28rpx","height":"80rpx"}' @tap="onSubmitTap" class="bg-red">提交</button>
			</view>
		</form>
		<w-picker  mode="dateTime" step="1" :current="false" :hasSecond="false" @confirm="dingdanshijianConfirm" ref="dingdanshijian" themeColor="#333333"></w-picker>
	</view>
</view>
</template>

<script>
	import wPicker from "@/components/w-picker/w-picker.vue";
	import xiaEditor from '@/components/xia-editor/xia-editor';
	import multipleSelect from "@/components/momo-multipleSelect/momo-multipleSelect";
	export default {
		data() {
			return {
				cross:'',
				ruleForm: {
				dingdanbianhao: this.generateOrderNumber(),
				lipinmingcheng: '',
				lipintupian: '',
				shuliang: '',
				duihuanjifen: '',
				jifen: '',
				dingdanshijian: '',
				dingdanbeizhu: '',
				zhanghao: '',
				yuangongzhanghao: '',
				yonghujifen: '',
				duihuanzhe: '',
				zhuzhi:'',
				shhf: '',
				},
				// 登录用户信息
				user: {},
				ro:{
				   dingdanbianhao : false,
				   lipinmingcheng : false,
				   lipintupian : false,
				   shuliang : false,
				   duihuanjifen : false,
				   jifen : false,
				   dingdanshijian : false,
				   dingdanbeizhu : false,
				   zhanghao : false,
				   yuangongzhanghao : false,
				   yonghujifen : false,
				   duihuanzhe : false,
				   sfsh : false,
				   shhf : false,
				   zhuzhi: false,
				},
				virtualPay: false,
			}
		},
		components: {
			wPicker,
			xiaEditor,
			multipleSelect,
		},
		computed: {
			baseUrl() {
				return this.$base.url;
			},


			jifen:{
			get: function () {
				return 1*this.ruleForm.shuliang*this.ruleForm.duihuanjifen
			}
			},

		},
		async onLoad(options) {
			if(options.virtualPay){
				this.virtualPay = true
			}
			this.ruleForm.dingdanshijian =  this.$utils.getCurDateTime();
			let table = uni.getStorageSync("nowTable");
			// 获取用户信息
			let res = await this.$api.session(table);
			this.user = res.data;
			
			// ss读取
			this.ruleForm.zhanghao = this.user.zhanghao
			this.ro.zhanghao = true;
			this.ruleForm.yuangongzhanghao = this.user.yuangongzhanghao
			this.ro.yuangongzhanghao = true;
			this.ruleForm.yonghujifen = this.user.jifen
			this.ro.yonghujifen = true;
			this.ro.zhuzhi = true;



			// 如果有登录，获取登录后保存的userid
			this.ruleForm.userid = uni.getStorageSync("appUserid")
			if (options.refid) {
				// 如果上一级页面传递了refid，获取改refid数据信息
				this.ruleForm.refid = Number(options.refid);
				this.ruleForm.nickname = uni.getStorageSync("nickname");
			}
			// 如果是更新操作
			if (options.id) {
				this.ruleForm.id = options.id;
				// 获取信息
				res = await this.$api.info(`duihuandingdan`, this.ruleForm.id);
				this.ruleForm = res.data;
			}
			// 跨表
			this.cross = options.cross;
			// 根据当前登录用户类型设置兑换者字段
			let userSession = JSON.parse(uni.getStorageSync("userSession") || "{}");
			if (userSession) {
				let tableName = uni.getStorageSync("nowTable");
				if (tableName === "laoren") {
					this.ruleForm.duihuanzhe = userSession.xingming || '';
				} else if (tableName === "yuangong") {
					this.ruleForm.duihuanzhe = userSession.yuangongxingming || '';
				} else {
					// 其他情况或兜底
					this.ruleForm.duihuanzhe = userSession.xingming || userSession.yuangongxingming || '';
				}
				// 新增：服务地址获取逻辑（与兑换者逻辑一致，假设laoren表服务地址字段为dizhi，yuangong表为zhuzhi，需根据实际字段调整）
				  if (tableName === "laoren") {
				    this.ruleForm.zhuzhi = userSession.zhuzhi || ''; // 假设laoren表服务地址字段为dizhi
				  } else if (tableName === "yuangong") {
				    this.ruleForm.zhuzhi = userSession.zhuzhi || ''; // 假设yuangong表服务地址字段为zhuzhi
				  } else {
				    this.ruleForm.zhuzhi = userSession.zhuzhi || userSession.zhuzhi || ''; // 兜底处理
				  }
			}
			if(options.cross){
				var obj = uni.getStorageSync('crossObj');
				for (var o in obj){
					if(o=='dingdanbianhao'){
						this.ruleForm.dingdanbianhao = obj[o];
						this.ro.dingdanbianhao = true;
						continue;
					}
					if(o=='lipinmingcheng'){
						this.ruleForm.lipinmingcheng = obj[o];
						this.ro.lipinmingcheng = true;
						continue;
					}
					if(o=='lipintupian'){
						this.ruleForm.lipintupian = obj[o].split(",")[0];
						this.ro.lipintupian = true;
						continue;
					}
					if(o=='shuliang'){
						this.ruleForm.shuliang = obj[o];
						this.ro.shuliang = true;
						continue;
					}
					if(o=='duihuanjifen'){
						this.ruleForm.duihuanjifen = obj[o];
						this.ro.duihuanjifen = true;
						continue;
					}
					if(o=='jifen'){
						this.ruleForm.jifen = obj[o];
						this.ro.jifen = true;
						continue;
					}
					if(o=='dingdanshijian'){
						this.ruleForm.dingdanshijian = obj[o];
						this.ro.dingdanshijian = true;
						continue;
					}
					if(o=='dingdanbeizhu'){
						this.ruleForm.dingdanbeizhu = obj[o];
						this.ro.dingdanbeizhu = true;
						continue;
					}
					if(o=='zhanghao'){
						this.ruleForm.zhanghao = obj[o];
						this.ro.zhanghao = true;
						continue;
					}
					if(o=='yuangongzhanghao'){
						this.ruleForm.yuangongzhanghao = obj[o];
						this.ro.yuangongzhanghao = true;
						continue;
					}
					if(o=='yonghujifen'){
						this.ruleForm.yonghujifen = obj[o];
						this.ro.yonghujifen = true;
						continue;
					}
					if(o=='duihuanzhe'){
						this.ruleForm.duihuanzhe = obj[o];
						this.ro.duihuanzhe = true;
						continue;
					}
					if(o=='zhuzhi'){
						this.ruleForm.zhuzhi = obj[o];
						this.ro.zhuzhi = true;
						continue;
					}
				}
			this.ruleForm.shuliang = 0;
			this.ro.shuliang = false;
			}
			this.styleChange()
			this.$forceUpdate()
			if (uni.getStorageSync('raffleType') && uni.getStorageSync('raffleType') != null) {
				uni.removeStorageSync('raffleType')
				setTimeout(() => {
					this.onSubmitTap()
				}, 300)
			}
		},
		methods: {
			styleChange() {
				this.$nextTick(()=>{
					// document.querySelectorAll('.app-update-pv . .uni-input-input').forEach(el=>{
					//   el.style.backgroundColor = this.addUpdateForm.input.content.backgroundColor
					// })
				})
			},

			// 多级联动参数


			// 日长控件选择日期时间
			dingdanshijianConfirm(val) {
				console.log(val)
				this.ruleForm.dingdanshijian = val.result;
				this.$forceUpdate();
			},


			lipintupianTap() {
				let _this = this;
				this.$api.upload(function(res) {
					_this.ruleForm.lipintupian = 'upload/' + res.file;
					_this.$forceUpdate();
					_this.$nextTick(()=>{
						_this.styleChange()
					})
				});
			},

			// 生成带日期时间格式的订单编号
			generateOrderNumber() {
				// 获取当前日期
				const date = new Date();
				
				// 格式化日期为yyyyMMdd
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				
				// 生成随机数，取值0-99
				const randomNum = Math.floor(Math.random() * 100).toString().padStart(2, '0');
				
				// 组合成订单号: yyyyMMddXX
				return `${year}${month}${day}${randomNum}`;
			},

			async onSubmitTap() {
			
				let that = this
				if(this.ruleForm.dingdanbianhao){
					this.ruleForm.dingdanbianhao = String(this.ruleForm.dingdanbianhao)
				}
				this.ruleForm.jifen = this.jifen
				if(Number(this.ruleForm.jifen)>Number(this.ruleForm.yonghujifen)){
					this.$utils.msg(`应付积分不能超过用户积分`);
					return
				}
				//跨表计算判断
				if((parseFloat(this.user.jifen) - parseFloat(this.ruleForm.jifen)) < 0){
					this.$utils.msg(`您的应付积分不足`);
					return false
				}
				var obj;
				obj = uni.getStorageSync('crossObj');
				var table = uni.getStorageSync('crossTable');
				//obj.shuliang = obj.shuliang - this.ruleForm.shuliang
				if((parseFloat(obj.shuliang) - parseFloat(this.ruleForm.shuliang))<0){
					this.$utils.msg("数量不足");
					return
				}
				if(this.ruleForm.shuliang<=0){
					this.$utils.msg("兑换数量必须大于0");
					return
				}
				if(this.ruleForm.shuliang&&(!this.$validate.isIntNumer(this.ruleForm.shuliang))){
					this.$utils.msg(`兑换数量应输入整数`);
					return
				}
				if(this.ruleForm.duihuanjifen&&(!this.$validate.isNumber(this.ruleForm.duihuanjifen))){
					this.$utils.msg(`兑换积分应输入数字`);
					return
				}
				if(this.ruleForm.jifen&&(!this.$validate.isNumber(this.ruleForm.jifen))){
					this.$utils.msg(`应付积分应输入数字`);
					return
				}
				if(this.ruleForm.yonghujifen&&(!this.$validate.isNumber(this.ruleForm.yonghujifen))){
					this.$utils.msg(`用户积分应输入数字`);
					return
				}
				if((!this.ruleForm.duihuanzhe)){
					this.$utils.msg(`兑换者不能为空`);
					return
				}
				//更新跨表属性
				var crossuserid;
				var crossrefid;
				var crossoptnum;
				if(this.cross){
					uni.setStorageSync('crossCleanType',true);
					var statusColumnName = uni.getStorageSync('statusColumnName');
					var statusColumnValue = uni.getStorageSync('statusColumnValue');
					if(statusColumnName!='') {
						if(!obj) {
							obj = uni.getStorageSync('crossObj');
						}
						if(!statusColumnName.startsWith("[")) {
							for (var o in obj){
								if(o==statusColumnName){
									obj[o] = statusColumnValue;
								}

							}
							var table = uni.getStorageSync('crossTable');
							await this.$api.update(`${table}`, obj);
						} else {
							   crossuserid=Number(uni.getStorageSync('appUserid'));
							   crossrefid=obj['id'];
							   crossoptnum=uni.getStorageSync('statusColumnName');
							   crossoptnum=crossoptnum.replace(/\[/,"").replace(/\]/,"");
						}
					}
				}
				if(crossrefid && crossuserid) {
					this.ruleForm.crossuserid=crossuserid;
					this.ruleForm.crossrefid=crossrefid;
					let params = {
						page: 1,
						limit:10,
						crossuserid:crossuserid,
						crossrefid:crossrefid,
					}
					let res = await this.$api.list(`duihuandingdan`, params);
					if (res.data.total >= crossoptnum) {
						this.$utils.msg(uni.getStorageSync('tips'));
						uni.removeStorageSync('crossCleanType');
						return false;
					} else {
				//跨表计算
						if(!obj) {
							obj = uni.getStorageSync('crossObj');
						}
						var table = uni.getStorageSync('crossTable');
						obj.shuliang = parseFloat(obj.shuliang) - parseFloat(this.ruleForm.shuliang)
						await this.$api.update(`${table}`, obj);
						let oet = {}
						if(this.ruleForm.id){
							await this.$api.update(`duihuandingdan`, this.ruleForm);
						}else{
							oet = await this.$api.add(`duihuandingdan`, this.ruleForm);
						 if(this.user.jifen>=0) {
							 this.user.jifen = parseFloat(this.user.jifen) - parseFloat(this.ruleForm.jifen)
							 await this.$api.update(uni.getStorageSync("nowTable"), this.user);
						 }
						}

						this.$utils.msgBack('提交成功');
					}
				} else {
				//跨表计算
					if(!obj) {
						obj = uni.getStorageSync('crossObj');
					}
					var table = uni.getStorageSync('crossTable');
					obj.shuliang = obj.shuliang - this.ruleForm.shuliang
					obj.jifen = this.jifen
					await this.$api.update(`${table}`, obj);
					let oet = {}
					if(this.ruleForm.id){
						await this.$api.update(`duihuandingdan`, this.ruleForm);
					}else{
						oet = await this.$api.add(`duihuandingdan`, this.ruleForm);
						 if(this.user.jifen>=0) {
							 this.user.jifen = parseFloat(this.user.jifen) - parseFloat(this.ruleForm.jifen)
							 await this.$api.update(uni.getStorageSync("nowTable"), this.user);
						 }
					}

					this.$utils.msgBack('提交成功');
				}
			},
			optionsChange(e) {
				this.index = e.target.value
			},
			bindDateChange(e) {
				this.date = e.target.value
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			toggleTab(str) {
				if(this.ro[str]){
					return false
				}
				this.$refs[str].show();
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		min-height: calc(100vh - 44px);
		box-sizing: border-box;
	}
</style>
